<template>
  <view class="page-container">
    <view class="form-container">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">收货人</text>
          <input
            class="input"
            type="text"
            v-model="formData.name"
            placeholder="请输入姓名"
          />
        </view>
        <view class="form-item">
          <text class="label">手机号码</text>
          <input
            class="input"
            type="number"
            v-model="formData.tel"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </view>
        <view class="form-item">
          <text class="label">性别</text>
          <view class="radio-group">
            <label class="radio" @tap="formData.gender = 1">
              <radio :checked="formData.gender == 1" color="#000000" />
              <text>先生</text>
            </label>
            <label class="radio" @tap="formData.gender = 2">
              <radio :checked="formData.gender == 2" color="#000000" />
              <text>女士</text>
            </label>
          </view>
        </view>
        <view class="form-item" @tap="chooseLocation">
          <text class="label">收货地址</text>
          <view class="address-content">
            <block v-if="formData.province">
              <text class="address-text"
                >{{ formData.addressDetail }}</text
              >
            </block>
            <text v-else class="input placeholder">点击选择所在地区</text>
            <u-icon name="arrow-right" size="16" color="#666"></u-icon>
          </view>
        </view>
        <view class="form-item">
          <text class="label">门牌号</text>
          <input
            class="input"
            type="text"
            v-model="formData.houseNumber"
            placeholder="请输入门牌号"
          />
        </view>
        <view class="form-item switch">
          <text class="label">设为默认地址</text>
          <switch
            :checked="formData.isDefault"
            @change="e => (formData.isDefault = e.detail.value)"
            color="#000000"
          />
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="footer">
      <button class="save-btn" @tap="saveAddress">保存</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        id: 0,
        name: '',
        tel: '',
        gender: 1, // 1-先生 2-女士
        province: '',
        city: '',
        county: '',
        addressDetail: '',
        houseNumber: '',
        isDefault: false,
        latitude: '',
        longitude: '',
        userId: ''
      },
      id: null // 编辑时的地址ID
    }
  },
  onLoad(options) {
    // 设置导航栏
    uni.setNavigationBarTitle({
      title: options.id ? '编辑地址' : '新增地址'
    })

    if (options.id && options.id != 0) {
      this.id = options.id
      this.getAddressDetail()
    }
  },
  methods: {
    // 获取地址详情
    async getAddressDetail() {
      try {
        const { errno, errmsg, data } = await this.$get('address/detail', {
          id: this.id
        })
        if (errno === 0) {
          this.formData = {
            ...this.formData,
            ...data,
            gender: data.gender || 1
          }
        } else {
          uni.showToast({
            title: errmsg,
            icon: 'none'
          })
        }
      } catch (error) {
        console.log(error)
        uni.showToast({
          title: '获取地址详情失败',
          icon: 'none'
        })
      }
    },
    // 选择位置
    chooseLocation() {
      uni.chooseLocation({
        success: res => {
          console.log('位置选择结果：', res)
          this.parseAddress(res.address)
          this.formData.latitude = res.latitude
          this.formData.longitude = res.longitude
          console.log(this.formData)
        },
        fail: err => {
          console.log('选择位置失败：', err)
          uni.showToast({
            title: '选择位置失败',
            icon: 'none'
          })
        }
      })
    },
    // 解析地址
    parseAddress(address) {
      this.formData.addressDetail = address
      const regex = /(.*?省)?(.*?市)?(.*?区|县)?/
      const matches = address.match(regex)
      if (matches) {
        this.formData.province = matches[1] || ''
        this.formData.city = matches[2] || ''
        this.formData.county = matches[3] || ''
      }
    },
    // 验证表单
    validateForm() {
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.tel) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        })
        return false
      }
      if (!/^1[3-9]\d{9}$/.test(this.formData.tel)) {
        uni.showToast({
          title: '手机号码格式不正确',
          icon: 'none'
        })
        return false
      }
      if (
        !this.formData.province ||
        !this.formData.city ||
        !this.formData.county
      ) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.houseNumber) {
        uni.showToast({
          title: '请输入门牌号',
          icon: 'none'
        })
        return false
      }
      return true
    },
    // 保存地址
    async saveAddress() {
      if (!this.validateForm()) return

      try {
        const params = {
          id: this.id || 0,
          name: this.formData.name,
          tel: this.formData.tel,
          gender: this.formData.gender,
          province: this.formData.province,
          city: this.formData.city,
          county: this.formData.county,
          addressDetail: this.formData.addressDetail,
          houseNumber: this.formData.houseNumber,
          isDefault: this.formData.isDefault,
          latitude: this.formData.latitude,
          longitude: this.formData.longitude
        }

        const { errno, errmsg, data } = await this.$post('address/save', params)
        if (errno === 0) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })

          // 如果是从订单确认页进入，则设置选中的地址
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2]
          if (prevPage && prevPage.route === 'pages/checkout/checkout') {
            prevPage.$vm.updateAddress(data)
          }

          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: errmsg,
            icon: 'none'
          })
        }
      } catch (error) {
        console.log(error)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/common/theme.scss';

.page-container {
  min-height: 100vh;
  background: $bg-main;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.form-container {
  padding: 24rpx;
}

.form-section {
  background: $bg-white;
  border-radius: 16rpx;
  padding: 0 30rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba($primary-pink, 0.05);
}

.form-item {
  display: flex;
  align-items: center;
  min-height: 100rpx;
  border-bottom: 2rpx solid rgba($primary-pink, 0.08);

  &:last-child {
    border-bottom: none;
  }

  .label {
    width: 200rpx;
    font-size: 28rpx;
    color: $primary-dark-pink;
  }

  .input {
    flex: 1;
    font-size: 28rpx;
    color: $primary-dark-pink;

    &.placeholder {
      color: $primary-light-pink;
    }
  }

  .address-content {
    flex: 1;
    display: flex;
    align-items: center;
    min-height: 40rpx;
    padding: 20rpx 0;

    .address-text {
      flex: 1;
      font-size: 28rpx;
      color: $primary-dark-pink;
      word-break: break-all;
      line-height: 1.6;
    }
  }

  &.switch {
    justify-content: space-between;
  }

  .radio-group {
    flex: 1;
    display: flex;
    align-items: center;

    .radio {
      display: flex;
      align-items: center;
      margin-right: 40rpx;

      text {
        font-size: 26rpx;
        color: $primary-dark-pink;
        margin-left: 8rpx;
      }
    }
  }
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 24rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background: $bg-white;
  box-shadow: 0 -4rpx 12rpx rgba($primary-pink, 0.05);

  .save-btn {
    height: 80rpx;
    line-height: 80rpx;
    background: $gradient-button;
    font-size: 30rpx;
    color: $bg-white;
    font-weight: 600;

    &:active {
      background: darken($primary-pink, 5%);
    }
  }
}
</style>
